package com.example.actionhandlers.actions;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;

import com.example.actionhandlers.AbstractAction;
import com.example.singletones.contextObj;

public class KillApplicationAction extends AbstractAction {
	private ActivityManager manager;

	public boolean isApplicable(JSONObject jsonObj) {
		try {
			return jsonObj.has("actionName")
					&& jsonObj.getString("actionName").equalsIgnoreCase(
							"killApplication");
		} catch (JSONException e) {
			return false;
		}
	}

	public boolean appkillFunction(String AppName) {

		List<RunningAppProcessInfo> procInfos = manager
				.getRunningAppProcesses();
		for (int itirator = 0; itirator < procInfos.size(); itirator++) {
			if (procInfos.get(itirator).processName
					.equalsIgnoreCase("com.waze")) {
				{
					if (execCommands("kill " + procInfos.get(itirator).pid) == false) {
						execCommands("kill " + procInfos.get(itirator).pid);
					}
					return true;
				}
			}
		}
		return false;
	}

	public Boolean execCommands(String command) {
		try {
			Runtime rt = Runtime.getRuntime();
			Process process = rt.exec("su");
			DataOutputStream os = new DataOutputStream(
					process.getOutputStream());

			os.writeBytes(command + "\n");
			os.flush();

			os.writeBytes("exit\n");
			os.flush();
			process.waitFor();
		} catch (IOException e) {
			return false;
		} catch (InterruptedException e) {
			return false;
		}
		return true;
	}

	public void performAction(JSONObject jsonObj) throws Exception {
		// TODO Auto-generated method stub

		contextObj.getInstance().getmContext();
		contextObj.getInstance().getmContext()
				.getSystemService(Context.ACTIVITY_SERVICE);
		for (int itirator = 0; itirator < 10; itirator++) {
			if (appkillFunction(jsonObj.getString("applicationName")) == false) {
				return;
			}
		}

	}

	public String getActionName() {
		return "killApplication";
	}

}
